package api

import (
	"encoding/json"
	"github.com/valyala/fasthttp"
	"permission/vigo_tool"
	"time"
	"gitlab.gaodun.com/golib/consul"
)

type vigoSid struct {
	GdSid string `json:"GDSID"`
}

var vigoSess = vigo_tool.NewSsoSessions()

// 生成唯一标识
func (bs *BaseServer) SetHandler(ctx *fasthttp.RequestCtx) {
	SetApiAllowCorsHeader(ctx)
	qArgs := ctx.QueryArgs()
	callback := qArgs.Peek("callback")
	source := qArgs.Peek("source")
	sess := vigoSess.StartFasthttp(ctx) // init the session
	valSess := sess.ID()
	// set cookie

	if ctx.Request.Header.Cookie(consul.GetEnvPath() + "GDSID") == nil {
		setCookie(ctx, valSess)
	}
	values := vigoSid{GdSid: valSess}
	str, _ := json.Marshal(&values)
	if len(source) > 0 {
		ctx.WriteString(string(str))
	} else {
		ctx.WriteString(string(callback) + "(" + string(str) + ")")
	}

	return
}

func setCookie(ctx *fasthttp.RequestCtx, sessionVal string)  {
	name := consul.GetEnvPath() + "GDSID"
	cookie := fasthttp.AcquireCookie()
	//cookie := &fasthttp.Cookie{}
	cookie.SetKey(name)
	cookie.SetValue(sessionVal)
	cookie.SetPath("/")
	cookie.SetHTTPOnly(false)
	cookie.SetDomain("gaodun.com")
	exp := time.Now().Add(5 * 356 * 24 * time.Hour) //RFC says 1 second, but let's do it 1 minute to make sure is working...
	cookie.SetExpire(exp)
	ctx.Response.Header.SetCookie(cookie)

}